<?php


namespace App\Traits;


use Illuminate\Database\Eloquent\Model;

trait ModelTrait
{
    /**
     * 安全的保存
     *
     * @param Model $model
     * @param array $attributes
     * @param string $message
     * @return Model
     * @throws \Exception
     */
    public function safeSave(Model $model, array $attributes, string $message = '保存失败！', int $code = 422)
    {
        $model->fill($attributes);
        if ($model->save() === false) {
            throw new \Exception($message, $code);
        }

        return $model;
    }

    /**
     * 安全的根据ID获取模型
     *
     * @param Model $model
     * @param $id
     * @param string $message
     * @param int $code
     * @return Model
     * @throws \Exception
     */
    public function findById(Model $model, $id, string $message = '当前ID数据不存在！', int $code = 422)
    {
        $model = $model->where($model->getKeyName(), $id)->first();
        if (!$model) {
            throw new \Exception($message, $code);
        }

        return $model;
    }

    /**
     * 根据where条件查询数据
     *
     * @param Model $model
     * @param array $where
     * @param string $message
     * @param array $with
     * @param int $code
     * @return \Illuminate\Database\Eloquent\Builder|Model|object
     * @throws \Exception
     */
    public function findWhere(Model $model, array $where, string $message = '当前ID数据不存在！', array $with = [], int $code = 422)
    {
        $query = $model->newQuery()->with($with);
        foreach ($where as $key => $value) {
            $query->where($key, $value);
        }
        $result = $query->first();
        if (!$result) {
            throw new \Exception($message, $code);
        }

        return $result;
    }

    /**
     * 安全的根据ID获取模型
     *
     * @param Model $model
     * @param $id
     * @param array $with
     * @param string $message
     * @param int $code
     * @return mixed
     * @throws \Exception
     */
    public function findByIdAndWith(Model $model, $id, array $with, string $message = '当前ID数据不存在！', int $code = 422)
    {
        $model = $model->with($with)->where($model->getKeyName(), $id)->first();
        if (!$model) {
            throw new \Exception($message, $code);
        }

        return $model;
    }


    /**
     * 安全的删除
     *
     * @param Model $model
     * @param $id
     * @param string $message
     * @param int $code
     * @throws \Exception
     */
    public function safeDestroy(Model $model, $id, string $message = '删除失败！', int $code = 422)
    {
        $result = $model->whereKey($id)->delete();
        if (!$result) {
            throw new \Exception($message, $code);
        }
    }


}
